import { Module } from 'vuex'
import { IloginState } from './type'
import { IRootState } from '../types'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestMenuByid
} from '@/service/login/login'
import { Iaccount } from '@/service/login/type'
import LocalCache from '@/utils/cache'
import router from '@/router/index'
import { mapMenusToRouter, mapMenusToPermissions } from '@/utils/map-menus'

const loginModule: Module<IloginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  mutations: {
    changetoken(state, token: string) {
      //把token值保存在sttae中
      state.token = token
    },
    //把用户信息保存在state中
    changeInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    //菜单信息
    changeUserMenu(state, userMenus: any) {
      state.userMenus = userMenus

      //在这里实现动态组件的逻辑
      //把获取到的url里面的路径，如果等于我们路由注册的路径那么我们把路由对应的组件通过addRouter添加为main的子路由
      const routes = mapMenusToRouter(userMenus)
      // console.log(routes)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
      //获取用户按钮的权限
      const permission = mapMenusToPermissions(userMenus)
      state.permissions = permission
    }
  },
  actions: {
    //1.账号登录的请求
    async accountLoginAction({ commit }, payload: Iaccount) {
      // console.log('执行了accountLoginAction', payload)
      const Loginresult = await accountLoginRequest(payload)
      const { id, token } = Loginresult.data
      //把token值传给mutations
      commit('changetoken', token)
      LocalCache.setCache('token', token)

      //2.请求用户的信息,根据id获取用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeInfo', userInfo)
      LocalCache.setCache('userInfo', userInfo)
      //3.根据用户id请求不同的菜单信息
      const Menu = await requestMenuByid(userInfo.role.id)
      const userMenus = Menu.data

      commit('changeUserMenu', userMenus)
      LocalCache.setCache('userMenus', userMenus)
      //4.跳到首页
      router.push('/main')
    },
    //使用loadLocalLogin方法，实现数据持久化，
    //原理就是，在main页面里调用这个函数，每次调用都会判断localstorage中有没有数据，
    //如果有则把数据重新提交给mutation来触发相对应的方法重新添加localstorsaeg中的数据
    loadLocalLogin({ commit }) {
      //获取localstorage里的信息，并判断有没有，如果有则把信息传递给token在次保存
      const token = LocalCache.getCache('token')
      if (token) {
        commit('changetoken', token)
      }
      const userInfo = LocalCache.getCache('userInfo')
      if (token) {
        commit('changeInfo', userInfo)
      }
      const userMenus = LocalCache.getCache('userMenus')
      if (token) {
        commit('changeUserMenu', userMenus)
      }
    }

    //手机登录的请求
    // phoneLoginAction({ commit }, payload) {
    //   console.log('执行了phoneLoginAction', payload)
    // }
  }
}

export default loginModule
